//
//  WPReadingSecondCollectionViewCell.m
//  wobingwoyi
//
//  Created by WGP on 16/8/23.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPReadingSecondCollectionViewCell.h"
#import "WPReadingFamousDoctorCell.h"

@interface WPReadingSecondCollectionViewCell ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UIView *noNetWorkView;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,assign)int page;

@end
@implementation WPReadingSecondCollectionViewCell

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = GlobalBgColor;
        [self noNetWorkView];
        
        self.page = 1;
        
        self.tableView = [[UITableView alloc] init];
        self.tableView.backgroundColor = GlobalBgColor;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.rowHeight = 170;
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5)];
        [self.tableView registerClass:[WPReadingFamousDoctorCell class] forCellReuseIdentifier:@"famousDoctor"];
        [self.contentView addSubview:self.tableView];
        
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.contentView);
        }];
        
        ReachabilityStatus status = [[RealReachability sharedInstance] currentReachabilityStatus];
        if (status == RealStatusNotReachable)
        {
            self.tableView.hidden = YES;
        }
        
        /* 配置下拉刷新控件 */
        MJRefreshNormalHeader *mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            //      刷新数据
            [self refreshData];
            
        }];
        self.tableView.mj_header = mj_header;
        [mj_header setTitle:@"下拉可以刷新" forState:MJRefreshStateIdle];
        [mj_header setTitle:@"松开立即刷新" forState:MJRefreshStatePulling];
        [mj_header setTitle:@"正在刷新" forState:MJRefreshStateRefreshing];
        mj_header.stateLabel.textColor = GLobalFontColor;
        mj_header.lastUpdatedTimeLabel.textColor = GLobalFontColor;
        
        //    上拉刷新控件
        MJRefreshAutoFooter *mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            [self loadMoreData];
            [mj_footer endRefreshing];
        }];
        self.tableView.mj_footer = mj_footer;
        mj_footer.automaticallyRefresh = NO;
        mj_footer.automaticallyHidden = NO;
    }
    return self;
}

-(UIView *)noNetWorkView
{
    if (_noNetWorkView == nil)
    {
        _noNetWorkView = [[UIView alloc] init];
        _noNetWorkView.backgroundColor = GlobalBgColor;
        [self.contentView addSubview:_noNetWorkView];
        
        [_noNetWorkView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.contentView);
        }];
        
        UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"noNetWork"]];
        [iconView sizeToFit];
        [_noNetWorkView addSubview:iconView];
        [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_noNetWorkView);
            make.top.equalTo(_noNetWorkView).offset(65);
        }];
        
        UILabel *tipLabel = [UILabel new];
        tipLabel.textColor = GloballightFontColor;
        tipLabel.font = [UIFont systemFontOfSize:14];
        tipLabel.text = @"网络请求失败,请检查您的网络设置";
        [_noNetWorkView addSubview:tipLabel];
        
        [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_noNetWorkView);
            make.top.equalTo(iconView.mas_bottom).offset(30);
        }];
        
        UIButton *loadAgainBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [loadAgainBtn setTitle:@"重新加载" forState:UIControlStateNormal];
        loadAgainBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [loadAgainBtn setTitleColor:GloballightFontColor forState:UIControlStateNormal];
        [loadAgainBtn setTitleColor:GlobalColor forState:UIControlStateHighlighted];
        [loadAgainBtn setBackgroundImage:[UIImage imageNamed:@"loadAgain_normal"] forState:UIControlStateNormal];
        [loadAgainBtn setBackgroundImage:[UIImage imageNamed:@"loadAgain_highlight"] forState:UIControlStateHighlighted];
        
        [loadAgainBtn addTarget:self action:@selector(loadAgainBtnDidClick:) forControlEvents:UIControlEventTouchDown];
        [_noNetWorkView addSubview:loadAgainBtn];
        
        [loadAgainBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(105);
            make.height.mas_equalTo(31);
            make.centerX.equalTo(_noNetWorkView);
            make.top.equalTo(tipLabel.mas_bottom).offset(16);
        }];
        
    }
    return _noNetWorkView;
}

-(void)setModels:(NSMutableArray *)models
{
    _models = models;
    
//    不满一页就隐藏
    if(self.models.count < 10)
    {
        self.tableView.mj_footer.hidden = YES;
    }
    else
    {
        self.tableView.mj_footer.hidden = NO;
    }
    
    [self.tableView reloadData];
}

#pragma mark - 数据源方法

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.models.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPReadingFamousDoctorCell *cell = [tableView dequeueReusableCellWithIdentifier:@"famousDoctor"];
    cell.model = self.models[indexPath.item];
    return cell;
}

#pragma mark - tableView的代理方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.delegate chargeCaseCellDidClickWith:self model:self.models[indexPath.item]];
}


-(void)refreshData
{
    NSString *url = @"record/searchRecord.do";;
    NSDictionary *dict = @{@"page":@(0),@"payable":@(1)};
    
    [self.tableView.mj_footer endRefreshing];
    
    [[WPViewModel sharedInstance] loadDataWithURL:url parameters:dict finished:^(NSArray *dictsArr, NSError *error) {
        
        if (dictsArr.count)
        {
            self.page = 1;
            
            if (self.models == nil)
            {
                self.models = [NSMutableArray array];
            }
            
            [self.models removeAllObjects];
            
            for (NSDictionary *dict in dictsArr)
            {
                WPMRModel *model = [WPMRModel yy_modelWithDictionary:dict];
                [self.models addObject:model];
            }
            
//            不满一页就隐藏
            if (dictsArr.count < 10)
            {
                self.tableView.mj_footer.hidden = YES;
            }
            else
            {
                self.tableView.mj_footer.hidden = NO;
            }
            
            [self.tableView reloadData];
        }
        
        [self.tableView.mj_header endRefreshing];
    }];
}

-(void)loadMoreData
{
    NSString *url = @"record/searchRecord.do";;
    NSDictionary *dict = @{@"page":@(self.page),@"payable":@(1)};
//    NSLog(@"%zd",self.page);
    
    [[WPViewModel sharedInstance] loadDataWithURL:url parameters:dict finished:^(NSArray *dictsArr, NSError *error) {
        
        if (dictsArr.count)
        {
            for (NSDictionary  *obj in dictsArr)
            {
                WPMRModel *model = [WPMRModel yy_modelWithDictionary:obj];
                [self.models addObject:model];
            }
            
            self.page++;
            //            刷新数据
            [self.tableView reloadData];
            
            if (dictsArr.count < 10)
            {
                self.tableView.mj_footer.hidden = YES;
            }
            else
            {
                self.tableView.mj_footer.hidden = NO;
            }
        }
        else
        {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
}

-(void)loadAgainBtnDidClick:(UIButton *)btn
{
    ReachabilityStatus status = [[RealReachability sharedInstance] currentReachabilityStatus];
    if (status != RealStatusNotReachable)
    {
        self.tableView.hidden = NO;
        if (self.loadAgainBlock)
        {
            self.loadAgainBlock();
        }
    }
}


@end
